package com.zmx.common.common.config.feign;

import com.zmx.common.common.invocation.InvocationInfo;
import com.zmx.common.common.invocation.InvocationInfoProxy;
import com.zmx.common.common.utils.JacksonUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @Description: 线程上下文 FeignClient 拦截器
 * @ClassName: InvocationInfoFilter
 * @Author zhaomxr
 * @Date 2022-01-13 19:35
 */
@Slf4j
public class InvocationInfoFeignClientInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 将线程上下文放入Feign的请求头中
        InvocationInfo invocationInfo = InvocationInfoProxy.get();
        if (invocationInfo != null) {
            try {
                String invocationInfoJson = JacksonUtil.toJsonString(invocationInfo);
                requestTemplate.header("INVOCATIONINFO", URLEncoder.encode(invocationInfoJson, "UTF-8"));
                requestTemplate.header("sys_code", "FeignClient");
            } catch (UnsupportedEncodingException e) {
                log.error("线程上下文信息设置错误", e);
            }
        }
    }
}
